package com.heima.wemediagateway.filter;

import com.heima.utils.common.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

//网关过滤器
@Component
@Order(-1)
public class AuthorizeFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2.判断是否是登录
        if (request.getURI().getPath().contains("/login")) {
            return chain.filter(exchange);//放行
        }
        //3.获取token
        String token = request.getHeaders().getFirst("token");
        //4.判断token是否存在
        if (StringUtils.isBlank(token)) {
            //HttpStatus.UNAUTHORIZED   401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //5.从token中取出载荷部分,判断token是否有效
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        //是否是过期   -1：有效，0：有效，1：过期，2：过期
        int i = AppJwtUtil.verifyToken(claimsBody);
        if (i == 0 || i == -1) {
            //在放行前给请求头里添加userid
            String id = claimsBody.get("id") + "";
            //构建新的请求对象
            ServerHttpRequest httpRequest = request.mutate().headers(httpHeaders -> httpHeaders.add("userId", id)).build();
            //构建新的交换机
            ServerWebExchange exchange1 = exchange.mutate().request(httpRequest).build();
            return chain.filter(exchange1);
        }
        //6.放行
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }
}
